package org.hospital.entity;

// default package

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import static org.hibernate.criterion.Example.create;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

/**
 * A data access object (DAO) providing persistence and search support for
 * TreatInfo entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see .TreatInfo
 * @author MyEclipse Persistence Tools
 */
@Transactional
public class TreatInfoDAO {
	private static final Logger log = LoggerFactory.getLogger(TreatInfoDAO.class);
	// property constants
	public static final String MEDICAL_CARD_ID = "medicalCardId";
	public static final String CLIENT_ID = "clientId";
	public static final String EXCUTOR_ID = "excutorId";
	public static final String DEPARTMENT_ID = "departmentId";
	public static final String CLINIC_ID = "clinicId";
	public static final String UNIT_PRICE = "unitPrice";
	public static final String EXCUTOR_COST = "excutorCost";
	public static final String CLINIC_COST = "clinicCost";

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	protected void initDao() {
		// do nothing
	}

	public List<TreatInfo> getByProperties(Map properties) {
		Criteria c = getCurrentSession().createCriteria(TreatInfo.class);
		c.add(Restrictions.allEq(properties));
		c.list();
		return c.list();
	}
	
	/**
	 * 获取执行者执行其他(门诊、部门)的治疗信息
	 * @param id 科室id(status = 0);门诊Id(status = 1);
	 * @param projectId 
	 * @param startTime
	 * @param endTime
	 * @param status 0:科室内;1:门诊内
	 * @return
	 */
	public List<TreatInfo> getOtherTreatInfo(int id,int projectId,long startTime,long endTime,int status){
		log.debug("getOtherTreatInfo instance");
		if(status != 0 && status != 1) {
			return null;
		}
		try {
			String hql = "";
			if(status == 1) {
				hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND ti.clinicId = :id "
					+ "AND mc.projectId = :projectId "
					+ "AND b.clinicId != :id "
					+ "AND b.status = 0 "
					+ "AND b.category = 'treatmentBill' "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			}
			if(status == 0) {
				hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND ti.departmentId = :id "
					+ "AND mc.projectId = :projectId "
					+ "AND b.departmentId != :id "
					+ "AND b.status = 0 "
					+ "AND b.category = 'treatmentBill' "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			}
			Query q = getCurrentSession().createQuery(hql);
			q.setParameter("id", id);
			q.setParameter("projectId", projectId);
			q.setParameter("startTime", new Date(startTime));
			q.setParameter("endTime", new Date(endTime));
			List<TreatInfo> result = q.list();
			log.debug("getOtherTreatInfo successful");
			return result;
		} catch (RuntimeException re) {
			log.error("getOtherTreatInfo failed", re);
			throw re;
		}
	}
	
	/**
	 * 获取门诊在[startTime,endTime]开的单的执行者医生治疗信息
	 * @param clinicId
	 * @param projectId
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<TreatInfo> getClinicTreatInfo(int clinicId, int projectId, long startTime,
			long endTime) {
		log.debug("getClinicTreatInfo instance");
		try {
			String hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND b.clinicId = :clinicId "
					+ "AND b.status = 0 "
					+ "AND b.category = 'treatmentBill' "
					+ "AND mc.projectId = :projectId "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			Query q = getCurrentSession().createQuery(hql);
			q.setParameter("clinicId", clinicId);
			q.setParameter("projectId", projectId);
			q.setParameter("startTime", new Date(startTime));
			q.setParameter("endTime", new Date(endTime));
			
			List<TreatInfo> result = q.list();
			log.debug("getClinicTreatInfo successful");
			return result;
		} catch (RuntimeException re) {
			log.error("getClinicTreatInfo failed", re);
			throw re;
		}
	}
	/**
	 * 获取科室在[startTime,endTime]开的单的执行者医生治疗信息
	 * @param departmentId
	 * @param projectId
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<TreatInfo> getDepartmentTreatInfo(int departmentId, int projectId, long startTime,
			long endTime) {
		log.debug("getDepartmentTreatInfo instance");
		try {
			String hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND b.status = 0 "
					+ "AND b.category = 'treatmentBill' "
					+ "AND b.departmentId = :departmentId "
					+ "AND mc.projectId = :projectId "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			Query q = getCurrentSession().createQuery(hql);
			q.setParameter("departmentId", departmentId);
			q.setParameter("projectId", projectId);
			q.setParameter("startTime", new Date(startTime));
			q.setParameter("endTime", new Date(endTime));
			
			List<TreatInfo> result = q.list();
			log.debug("getDepartmentTreatInfo successful");
			return result;
		} catch (RuntimeException re) {
			log.error("getDepartmentTreatInfo failed", re);
			throw re;
		}
	}
	
	/**
	 * 获取自身执行者执行治疗信息
	 * @param excutor
	 * @param id 科室id(status = 0);门诊Id(status =1);
	 * @param projectId
	 * @param startTime
	 * @param endTime
	 * @param status  0:科室内;1:门诊内
	 * @return
	 */
	public List<TreatInfo> getSelfExcutorTreatInfo(Employee excutor,int id, int projectId, long startTime,
			long endTime,int status){
		log.debug("getSelfExcutorTreatInfo instance");
		if(status != 0 && status != 1) {
			return null;
		}
		try {
			String hql = "";
			if(status == 1) {
				hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND b.status = 0 "
					+ "AND b.category = 'treatmentBill' "
					+ "AND ti.clinicId = :id "  //保证治疗信息是该门诊下的
					+ "AND mc.projectId = :projectId "
					+ "AND ti.excutorId = :excutorId "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			}
			if(status == 0) {
				hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND b.status = 0 "
					+ "AND b.category = 'treatmentBill' "
					+ "AND ti.departmentId = :id "  //保证治疗信息是该科室下的
					+ "AND mc.projectId = :projectId "
					+ "AND ti.excutorId = :excutorId "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			}
			
			Query q = getCurrentSession().createQuery(hql);
			q.setParameter("id", id);
			q.setParameter("projectId", projectId);
			q.setParameter("excutorId", excutor.getEmployeeId());
			q.setParameter("startTime", new Date(startTime));
			q.setParameter("endTime", new Date(endTime));
			
			List<TreatInfo> result = q.list();
			log.debug("getSelfExcutorTreatInfo successful");
			return result;
		} catch (RuntimeException re) {
			log.error("getSelfExcutorTreatInfo failed", re);
			throw re;
		}
	}
	
	/**
	 * 获取治疗项目给分院执行者治疗的所有信息
	 * @param excutor
	 * @param clinicId
	 * @param projectId
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<TreatInfo> getOtherExcutorTreatInfo(Employee excutor,int clinicId, int projectId, long startTime,
			long endTime){
		log.debug("getOtherExcutorTreatInfo instance");
		try {
			String hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND b.status = 0 "
					+ "AND b.category = 'treatmentBill' "
					+ "AND b.clinicId = :clinicId "
					+ "AND ti.clinicId != :clinicId "  //保证不是该门诊下的
					+ "AND mc.projectId = :projectId "
					+ "AND ti.excutorId = :excutorId "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			Query q = getCurrentSession().createQuery(hql);
			q.setParameter("clinicId", clinicId);
			q.setParameter("projectId", projectId);
			q.setParameter("excutorId", excutor.getEmployeeId());
			q.setParameter("startTime", new Date(startTime));
			q.setParameter("endTime", new Date(endTime));
			
			List<TreatInfo> result = q.list();
			log.debug("getOtherExcutorTreatInfo successful");
			return result;
		} catch (RuntimeException re) {
			log.error("getOtherExcutorTreatInfo failed", re);
			throw re;
		}
	}
	
	//TODO 默认了执行医生没有换到其他门诊执行治疗 
	
	/**
	 * 获取部门开的单其他门诊执行信息\获取部门开的单，本门诊其他部门门诊执行信息
	 * @param excutor
	 * @param clinicId //查询科室所属门诊
	 * @param departmentId //查询科室
	 * @param projectId
	 * @param startTime
	 * @param endTime
	 * @param status 0(获取部门开的单其他门诊执行医生执行信息);1(获取部门开的单，本门诊其他部门执行医生执行信息);
	 * @return
	 */
	public  List<TreatInfo> getDepartmentOtherTreatInfo(Employee excutor,int clinicId,int departmentId,int projectId,long startTime
			,long endTime,int status) {
		log.debug("getDepartmentOtherTreatInfo instance");
		try {
			String hql = "";
			if(status == 0) {
				hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND b.status = 0 " //有效单据
					+ "AND b.category = 'treatmentBill' "
					+ "AND b.departmentId = :departmentId " //本科室单据
					+ "AND ti.clinicId != :clinicId "  //保证不是该门诊下的
					+ "AND mc.projectId = :projectId "
					+ "AND ti.excutorId = :excutorId "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			}
			if(status == 1) {
				hql = "SELECT ti "
					+ "FROM TreatInfo as ti,MedicalCard as mc,Bill as b "
					+ "WHERE ti.medicalCardId = mc.medicalCardId "
					+ "AND mc.billId = b.billId "
					+ "AND b.status = 0 " //有效单据
					+ "AND b.category = 'treatmentBill' "
					+ "AND b.departmentId = :departmentId " //本科室单据
					+ "AND ti.clinicId = :clinicId " //本门诊
					+ "AND ti.departmentId != :departmentId " //不同科室
					+ "AND mc.projectId = :projectId "
					+ "AND ti.excutorId = :excutorId "
					+ "AND ti.treatTime >= :startTime "
					+ "AND ti.treatTime < :endTime ";
			}
			Query q = getCurrentSession().createQuery(hql);
			q.setParameter("clinicId", clinicId);
			q.setParameter("departmentId", departmentId);
			q.setParameter("projectId", projectId);
			q.setParameter("excutorId", excutor.getEmployeeId());
			q.setParameter("startTime", new Date(startTime));
			q.setParameter("endTime", new Date(endTime));
			
			List<TreatInfo> result = q.list();
			log.debug("getClinicTreatInfo successful");
			return result;
		} catch (RuntimeException re) {
			log.error("getClinicTreatInfo failed", re);
			throw re;
		}
	}
	public void save(TreatInfo transientInstance) {
		log.debug("saving TreatInfo instance");
		try {
			getCurrentSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(TreatInfo persistentInstance) {
		log.debug("deleting TreatInfo instance");
		try {
			getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public TreatInfo findById(java.lang.Integer id) {
		log.debug("getting TreatInfo instance with id: " + id);
		try {
			TreatInfo instance = (TreatInfo) getCurrentSession().get(
					"org.hospital.entity.TreatInfo", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<TreatInfo> findByExample(TreatInfo instance) {
		log.debug("finding TreatInfo instance by example");
		try {
			List<TreatInfo> results = (List<TreatInfo>) getCurrentSession()
					.createCriteria("TreatInfo").add(create(instance)).list();
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding TreatInfo instance with property: " + propertyName + ", value: " + value);
		try {
			String queryString = "from TreatInfo as model where model." + propertyName + "= ?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<TreatInfo> findByMedicalCardId(Object medicalCardId) {
		return findByProperty(MEDICAL_CARD_ID, medicalCardId);
	}

	public List<TreatInfo> findByClientId(Object clientId) {
		return findByProperty(CLIENT_ID, clientId);
	}

	public List<TreatInfo> findByExcutorId(Object excutorId) {
		return findByProperty(EXCUTOR_ID, excutorId);
	}

	public List<TreatInfo> findByDepartmentId(Object departmentId) {
		return findByProperty(DEPARTMENT_ID, departmentId);
	}

	public List<TreatInfo> findByClinicId(Object clinicId) {
		return findByProperty(CLINIC_ID, clinicId);
	}

	public List<TreatInfo> findByUnitPrice(Object unitPrice) {
		return findByProperty(UNIT_PRICE, unitPrice);
	}

	public List<TreatInfo> findByExcutorCost(Object excutorCost) {
		return findByProperty(EXCUTOR_COST, excutorCost);
	}

	public List<TreatInfo> findByClinicCost(Object clinicCost) {
		return findByProperty(CLINIC_COST, clinicCost);
	}

	public List findAll() {
		log.debug("finding all TreatInfo instances");
		try {
			String queryString = "from TreatInfo";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public TreatInfo merge(TreatInfo detachedInstance) {
		log.debug("merging TreatInfo instance");
		try {
			TreatInfo result = (TreatInfo) getCurrentSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(TreatInfo instance) {
		log.debug("attaching dirty TreatInfo instance");
		try {
			getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(TreatInfo instance) {
		log.debug("attaching clean TreatInfo instance");
		try {
			getCurrentSession().buildLockRequest(LockOptions.NONE).lock(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static TreatInfoDAO getFromApplicationContext(ApplicationContext ctx) {
		return (TreatInfoDAO) ctx.getBean("TreatInfoDAO");
	}
}